import { FOURLEVELMENU, ORGNODATA } from '../mutations-type'
import { axiosGet } from '@/api/sysSetting.js'
import renderUrl from "@/api/apiHost";
// 登录状态
const fuzzyQuery = (list) => {
  list.map(item => {
    if (item.children && item.children.length > 0) {
      fuzzyQuery(item.children)
    } else {
      delete item['children']
    }
  })
}
const state = {
  fourListMenu: [],
  orgNoList: []
}

const actions = {
  getChildList ({ state, commit }, flag) {
    commit('FOURLEVELMENU', flag)
  },
  //单位名称，在登陆的时候调用
  getOrgNoList ({ state, dispatch }) {
    axiosGet(
      renderUrl("profile")+'/profile/myHome/customerArchives/userEnergyArchives/customerArchivesManage/getBOrgInfoSelect'
    ).then(res => {
      return new Promise(async resolve => {
        // store 赋值
        fuzzyQuery(Array.isArray(res.result) ? res.result : [res.result])
        state.orgNoList = Array.isArray(res.result) ? res.result : [res.result];
        console.log(Array.isArray(res.result) ? res.result : [res.result],"Array.isArray(res.result) ? res.result : [res.result]")
        // 持久化
        await dispatch('admin/db/set', {
            dbName: 'sys',
            path: 'orgInfo',
            value: Array.isArray(res.result) ? res.result : [res.result],
            user: true
        }, { root: true });
        // end
        resolve();
    })
      // commit('ORGNODATA', Array.isArray(res.result) ? res.result : [res.result])
    })
  },
  /**
   * 获取组织机构
   * @param {*} param0   初始化orgNoList
   */
  getOrg ({state, dispatch}) {
    return new Promise(async resolve => {
      // store 赋值
      state.orgNoList = await dispatch('admin/db/get', {
          dbName: 'sys',
          path: 'orgInfo',
          defaultValue: [],
          user: true
      }, { root: true });
      // end
      resolve();
    })
  },
  /**
   * 清空组织机构
   * @param {*} param0
   * @param {*} orgInfo
   */
  clearOrg({state, dispatch},orgInfo) {
    return new Promise(async resolve => {
      // store 赋值
      state.orgNoList = orgInfo
      // 持久化
      await dispatch('admin/db/set', {
          dbName: 'sys',
          path: 'orgInfo',
          value: orgInfo,
          user: true
      }, { root: true });
      // end
      resolve();
  })
  }
}
const mutations = {
  [FOURLEVELMENU] (state, flag) {
    state.fourListMenu = flag
  },
  [ORGNODATA] (state, flag) {
    if (flag.length === 0) {
      state.orgNoList = []
    } else {
      fuzzyQuery(flag)
      state.orgNoList = flag
    }
  }

}
export default {
  namespaced: true,
  state,
  actions,
  mutations
}
